package com.lims;


import com.lims.utils.FileUtil;

import java.io.File;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.*;

/**
 * @author limaosheng
 * @create 17:01 2021/12/6
 * 生成适合smart-doc的实体类
 */
public class 生成适合smartDoc的实体类 {
    //包名
    private static String packagePath = "自动生成实体类";
    public static String author = "limaosheng";
    //是否覆盖原文件
    public final static boolean isFileOverride = false;
    /**
     * 数据库
     */
    public final static String DB_URL = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8";
    public final static String DB_USER = "root";
    public final static String DB_PWD = "123456";

    public static void main(String[] args) {
        gen("test_user");
    }

    //生成
    public static void gen(String tableName) {
        String tableComment = "用户表";
        //获取所有字段信息
        List<Map<String, Object>> list = getConlumn(tableName);
        //获取表ID注解
        for (Map<String, Object> map : list) {
            String column_name = map.get("COLUMN_NAME").toString();
            if ("id".equals(column_name)) {
                String column_comment = map.get("COLUMN_COMMENT").toString();
                if (column_comment.contains("主键")) {
                    tableComment = column_comment.replaceAll("主键", "");
                }
            }
        }
        StringBuffer sb = new StringBuffer();
        sb.append("package " + packagePath + ";\r\n\r\n");
        sb.append("import lombok.Data;\r\n");
        sb.append("import java.time.LocalDateTime;\r\n");
        sb.append("/**\r\n");
        sb.append(" *\r\n");
        sb.append(" * @author " + author + "\r\n");
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = sf.format(new Date());
        sb.append(" * @time " + date + "\r\n");
        sb.append(" * @desc " + tableComment + "\r\n");
        sb.append(" */\r\n");
        sb.append("@Data\r\n");
        sb.append("public class " + initcap(tableName) + " {\r\n\r\n");

        for (Map<String, Object> map : list) {
            String column_name = map.get("COLUMN_NAME").toString();
            String colname = getCamelStr(column_name);//转成驼峰式
            String column_comment = map.get("COLUMN_COMMENT").toString();//备注
            String is_nullable = map.get("IS_NULLABLE").toString();//是否可为空{NO,YES}
            String column_type = map.get("COLUMN_TYPE").toString();//带长度类型，目前：int(11)，varchar(30)，datetime，date，decimal(12,2)
            String data_type = map.get("DATA_TYPE").toString();//不带长度，与column_type相比，没用括号以及括号内长度
            //String character_maximum_length = map.get("character_maximum_length").toString();//长度，只有varchar有值
            String column_key = map.get("COLUMN_KEY").toString();//主键或者索引，PRI主键，MUL索引

            sb.append("    /**\r\n");
            sb.append("     * " + column_comment + "\r\n");
            sb.append("     */\r\n");
            String javaType = sqlType2JavaType(data_type);
            sb.append("\tprivate " + javaType + " " + colname + ";\r\n");
        }
        sb.append("\r\n");
        sb.append("}\r\n");
        try {
            String path = System.getProperty("user.dir") + "/src/test/java/自动生成实体类";
            File file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }
            String resPath = path + "/" + initcap(tableName) + ".java";
            System.out.println("文件地址：" + resPath);
            FileUtil.write(resPath, sb.toString());
        } catch (Exception e) {
            System.out.println("生成失败");
        }
    }

    private static List<Map<String, Object>> getConlumn(String tableName) {
        //获取表结构
        String colSql = "select column_name,column_comment,is_nullable,column_type,data_type,character_maximum_length,column_key from information_schema.columns where table_name= '" + tableName + "' and table_schema = 'smart_community'";
        Connection conn = null;
        List<Map<String, Object>> conlumns = new ArrayList<>();
        try {
            conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PWD);
            PreparedStatement ps = conn.prepareStatement(colSql);
            ResultSet rs = ps.executeQuery();
            ResultSetMetaData md = rs.getMetaData();
            int columnCount = md.getColumnCount();
            while (rs.next()) {
                Map<String, Object> rowData = new HashMap<String, Object>();
                for (int i = 1; i <= columnCount; i++) {
                    rowData.put(md.getColumnName(i), rs.getObject(i));
                }
                conlumns.add(rowData);
            }
        } catch (Exception throwables) {
            throwables.printStackTrace();
        } finally {
            closeConn(conn);
        }
        return conlumns;
    }
    public static void closeConn(Connection conn) {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    /**
     * 把输入字符串的首字母改成大写
     *
     * @param str
     * @return
     */
    public static String initcap(String str) {
        char[] ch = str.toCharArray();
        if (ch[0] >= 'a' && ch[0] <= 'z') {
            ch[0] = (char) (ch[0] - 32);
        }
        return getCamelStr(new String(ch));
    }

    // 例：user_name --> userName
    public static String getCamelStr(String s) {
        while (s.indexOf("_") > 0) {
            int index = s.indexOf("_");
            // System.out.println(s.substring(index+1, index+2).toUpperCase());
            s = s.substring(0, index) + s.substring(index + 1, index + 2).toUpperCase() + s.substring(index + 2);
        }
        return s;
    }

    public static String sqlType2JavaType(String sqlType) {
        String javaType = "String";
        if ("int".equals(sqlType)) {
            javaType = "Integer";
        } else if ("datetime".equals(sqlType) || "date".equals(sqlType)) {
            javaType = "LocalDateTime";
        } else if ("decimal".equals(sqlType)) {
            javaType = "BigDecimal";
        } else if ("bigint".equals(sqlType)) {
            javaType = "Long";
        }
        return javaType;
    }
}
